<template>
  <div>
    <!-- //页面工具条的表单 -->
    <el-form ref="form" :model="searchform" :inline="true">
      <el-form-item>
        <el-input v-model="searchform.categoryname" placeholder="请输入要搜索的内容"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="searchCategoryInfo" style="margin-right:2px">搜索</el-button>
        <el-button type="primary" style="margin-right:3px" @click="dialogFormVisible = true">新建类别</el-button>
        <el-button type="primary" style="margin-right:5px" @click="resetDateFilter">清除状态过滤器</el-button>
        <!-- //气泡框 -->
        <el-popconfirm title="确定要批量删除吗？" @confirm="deleteCategory">
          <el-button slot="reference" type="danger" style="margin-left:3px" :disabled="deleteAllBtnStu">批量删除
          </el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <!-- 主要内容表格 -->
    <el-table :data="tableData" ref="filterTable" @selection-change="selectionChange" border row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" style="width:100%;margin-bottom: 10px;"
              :cell-style="{ padding: '2px' }">
      <el-table-column type="selection" width="50">
      </el-table-column>
      <el-table-column label="类别名称" width="280px" prop="name">
      </el-table-column>
      <el-table-column label="类别封面" width="200" prop="avatar">
        <!-- 头像    scope代表循环中的每一行 -->
        <template slot-scope="scope">
          <el-image style="height: 100px; " :src="scope.row.avatar"></el-image>
        </template>
      </el-table-column>

      <el-table-column label="数量占比" prop="cpercentage">
        <template slot-scope="scope">
          <el-progress :text-inside="true" :stroke-width="20" :percentage="scope.row.cpercentage" status="exception">
          </el-progress>
        </template>
      </el-table-column>

      <el-table-column label="状态" prop="statu" width="100"
                       :filters="[{ text: '使用中', value: '使用中' }, { text: '未使用', value: '未使用' }]"
                       :filter-method="filterTag"
                       filter-placement="bottom-end">
        <template slot-scope="scope">

          <el-tag size="mini" :type="scope.row.statu === '未使用' ? 'danger' : 'success'"
                  disable-transitions>{{ scope.row.statu }}
          </el-tag>
          <!-- <el-tag size="mini" v-else-if="scope.row.statu === 0" type='danger' disable-transitions>未使用</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created" width="200">
        <!-- prop对应列内容的字段名 -->
        <template slot-scope="scope">
          {{ scope.row.created | fmtDate }}
        </template>
      </el-table-column>
      <el-table-column label="最新修改时间" prop="updated" width="200">
        <!-- prop对应列内容的字段名 -->
        <template slot-scope="scope">
          {{ scope.row.updated | fmtDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <!-- prop对应列内容的字段名 -->
        <template slot-scope="scope">
          <el-button type="text" @click="editCategory(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="确认要删除该类别信息吗？" @confirm="deleteCategory(scope.row.id)">
            <el-button slot="reference" type="text">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>


    </el-table>

    <!-- 对话框 -->
    <el-dialog title="新建类别" :visible.sync="dialogFormVisible" width="550px" :before-close="handleClose">
      <el-form :model="CategoryForm" ref="CategoryForm" label-width="100px" :rules="rules">
        <el-form-item label="类别封面" label-width="100px">
          <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
                     :on-success="handleAvatarSuccess" :headers="headers">
            <!-- :headers="headers" -->
            <!-- //上传成功会获得路径回显 -->
            <img v-if="CategoryForm.avatar" :src="CategoryForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <!-- 下拉列表便是父菜单以及子菜单 -->
        <el-form-item label="上级类别" prop="parentId">
          <el-select v-model="CategoryForm.parentId" placeholder="请选择上级菜单">
            <template v-for="(item, index) in tableData">
              <el-option :key="item.id" :label="item.name" :value="item.id">
              </el-option>
              <!-- 二级菜单 -->
              <template v-for="(childCategory, i) in item.children">
                <el-option :label="childCategory.name" :value="childCategory.id" :key="childCategory.id">
                  <span style="padding-left: 20px;">{{ '-' + childCategory.name }}</span>
                </el-option>
              </template>
            </template>
          </el-select>
        </el-form-item>


        <el-form-item label="类别名称" label-width="100px" prop="name">
          <el-input v-model="CategoryForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="数量占比" label-width="100px" prop="cpercentage">
          <el-input v-model="CategoryForm.cpercentage" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="类别状态" label-width="100px" prop="statu">
          <el-radio-group v-model="CategoryForm.statu">
            <el-radio :label="1">使用中</el-radio>
            <el-radio :label="0">未使用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('CategoryForm')">保存菜单</el-button>
          <el-button @click="resetForm('CategoryForm')">重置</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
    <!-- 显示分页功能 -->
    <el-pagination layout="prev, sizes,pager, next, total, jumper " :total="total" :page-size="size"
                   :page-sizes="[5,10,15,20]" :current-page="current" style="margin-top: 20px">
    </el-pagination>


  </div>
</template>

<script>
export default {
  data() {
    return {
      current: 0,
      size: 0,
      total: 0,
      tableData: [],
      selection: [],
      searchform: {},
      CategoryForm: {},
      dialogFormVisible: false,
      deleteAllBtnStu: true,
      headers: {
        token: localStorage.getItem('token')
      },
      rules:
          {
            name: [{required: true, message: '请输入类别名！', trigger: 'blur'}],
            cpercentage: [{required: true, message: '请输入数量占比！', trigger: 'blur'}],
            parentId: [{required: true, message: '请选择上级类别！', trigger: 'blur'}],
            statu: [{required: true, message: '请选择类别状态！', trigger: 'blur'}],
          },

    }
  },

  filters: {
    fmtDate: (value) => {
      let date = new Date(value)
      let y = date.getFullYear()
      let M = (date.getMonth() + 1).toString().padStart(2, '0')
      let d = date.getDate().toString().padStart(2, '0')
      let h = date.getHours().toString().padStart(2, '0')
      let m = date.getMinutes().toString().padStart(2, '0')
      let s = date.getSeconds().toString().padStart(2, '0')
      //2023年09 月09日 22:11:0
      //ES6 拼接占位符y+'年'+M+'月
      return `${y}年${M}月${d}日 ${h}:${m}:${s}`
    }
  },
  created() {
    this.loadCategoryList();
  },
  methods: {
    filterTag(value, row) {
      return row.statu == value;
    },
    resetDateFilter() {
      this.$refs.filterTable.clearFilter();
    },
    resetForm() {
      this.CategoryForm = {}
      this.$refs.CategoryForm.resetFields();
    },
    handleAvatarSuccess(response, file) {
      //上传封面成功。，服务器返回一个上传后的图片网络地址
      this.CategoryForm.avatar = response.data
    },
    handleClose() {
      this.dialogFormVisible = false
      this.resetForm('CategoryForm')
    },
    searchCategoryInfo() {

    },
    deleteCategory(id) {
      //如果id有值表示单个的删除，没有id表示批量删除（批量用户数据在this.selection数组里面）
      let ids = [];//ids数组要删除的所有用户数据
      id ? ids.push(id) : this.selection.forEach(u => {
        ids.push(u.id)
      })
      this.$axios.post('/system/category/delete', ids).then(response => {
        this.$message({
          message: response.data.message,
          type: 'success',
          showClose: true,
          onClose: () => {
            this.loadCategoryList()
          }
        })
      })
    },
    selectionChange(value) {
      this.selection = value
      if (this.selection) {
        this.deleteAllBtnStu = (this.selection.length == 0)
      }
    },
    editCategory(id) {
      this.$axios('/system/category/info/' + id).then(response => {
        this.CategoryForm = response.data.data
        this.dialogFormVisible = true
      })
    },
    //页面加载数据
    loadCategoryList() {
      this.$axios.get('/system/category/list', {
        current: this.current,
        size: this.size
      }).then(response => {
        this.tableData = response.data.data.records
        this.size = response.data.data.size
        this.total = response.data.data.total
        this.current = response.data.data.current
      })
    },
    submitForm(formName) {
      this.$refs.CategoryForm.validate((valid) => {
        if (valid) {
          this.$axios.post('/system/category/' + (this.CategoryForm.id ? 'update' : 'save')).then(response => {
            this.$message({
              message: response.data.message,
              type: 'success',
              // showClose: true,
              duration: 1200,//1.5秒后自动关闭对话框
              onClose: () => {
                this.loadCategoryList()  //需要重新加载用户信息
                this.dialogFormVisible = false //对话框是否显示
                this.resetForm(formName)  //重置表单
              }
            })

          })
        }
      })
    },
  },
  components: {}
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #9b9a9a;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-table__body {
  font-size: 14px;
}

.el-button:hover {
  color: #333
}

.el-popconfirm-reference {
  cursor: pointer;
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  font-size: 12px;
  padding: 2px 6px;
}

.el-table-column--selection {
  text-align: center;
}

.el-avatar {
  border-radius: 50%;
}

.el-divider {
  margin: 0 6px;
}

/*上传头像*/
/*.avatar-uploader {*/
/*  border: 1px dashed #d9d9d9;*/
/*  border-radius: 6px;*/
/*  cursor: pointer;*/
/*  position: relative;*/
/*  overflow: hidden;*/
/*}*/

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-dialog {
  text-align: center;
}

/* Style the dialog header */
.el-dialog__header {
  background-color: #2f4050;
  color: #fff;
  border-radius: 4px 4px 0 0;
  border-bottom: none;
}

/* Style the dialog title */
.el-dialog__title {
  font-size: 22px;
  font-weight: bold;
  padding: 20px;
}

/* Style the form labels */
.el-form-item__label {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

/* Style the input fields */
.el-input__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  color: #606266;
}

/* Style the radio buttons */


.el-radio-button {
  flex: 1;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
  border-radius: 0 0 4px 4px;
}

.dialog-footer .el-button {
  margin-left: 10px;
  border-radius: 4px;
}

.dialog-footer .el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.dialog-footer .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.dialog-footer .el-button--primary:active {
  background-color: #3a8ee6;
  border-color: #3a8ee6;
}

.dialog-footer .el-button--default {
  color: #333;
  border-color: #dcdfe6;
}

.dialog-footer .el-button--default:hover {
  color: #409EFF;
  border-color: #409EFF;
}
</style>
